<?php

namespace Frieza\Modules\ConstructionPurchase\Controllers;

use App\Admin\Extensions\Tools\GridView;
use App\Admin\Extensions\Tools\PreviewButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\model\ConstructionPurchase\ConstructionProcess;
use Doraemon\model\ConstructionPurchase\ConstructionProcessModule;
use Doraemon\model\ConstructionPurchase\ConstructionProcessModuleContent;
use Doraemon\model\ConstructionPurchase\ConstructionProcessTab;
use Doraemon\service\ConstructionPurchase\Construction;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ProcessController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $copiedScript = <<<SCRIPT
$('.grid-table').on('click', '.grid-column-copyable', (function (e) {
            var content = $(this).data('content');
            var temp = $('<input>');
            $("body").append(temp);
            temp.val(content).select();
            document.execCommand("copy");
            temp.remove();
            $(this).tooltip('show');
        }));
SCRIPT;

        Admin::script($copiedScript);
        $list = ConstructionProcess::selectListByWhere(['status' => ConstructionProcess::STATUS_NORMAL, 'ORDER' => ['id' => 'ASC']]);
        $ids = array_column($list, 'id');
        $tabArr = $ids ? ConstructionProcessTab::selectListByWhere(['process_id' => $ids, 'status' => ConstructionProcessTab::STATUS_NORMAL]) : [];
        $tabList = [];
        foreach ($tabArr as $row) {
            $tabList[$row['process_id']][] = $row;
        }
        foreach ($list as &$row) {
            $row['tab_list'] = $tabList[$row['id']] ?? [];
        }

        $gridModel = new GridDataModel($list);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID');
                $grid->column('name', '施工工序名称');
                $grid->column('tab_list', 'Tab')->display(function () {
                    $format = [];
                    if ($this->tab_list) {
                        foreach ($this->tab_list as $tabRow) {
                            $url = url('/admin/constructionPurchase/process/' . $this->id . '/edit/' . $tabRow['id'] . '/edit');
                            $format[] = "<a href='{$url}'>{$tabRow['name']}</a>";
                        }
                    }
                    return $format;
                })->label('default');
                $grid->column('link', '链接')->display(function () {
                    $url = Hhzurl::H5ConstructionProcessLink($this->id);
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $url . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i>复制</a>';
                    $html .= '&nbsp;&nbsp;<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'500px\', \'600px\'],content: \'' . $url . '\'});">预览</a></li>';
                    $html .= '</a>';
                    $html .= '</ul>';
                    return $html;
                })->width(100);

            }
        );

        return $content
            ->header('施工工序列表')
            ->breadcrumb(['text' => '施工工序列表'])
            ->row($grid->render());
    }

    public function editProcess(Content $content, Request $request, $id = 0)
    {
        $tab = new Tab();
        $form = $this->getProcessForm($id);
        $tab->add('基础信息', $form);
        if ($id) {
            $gride = $this->getProcessTabGride($id);
            $tab->add('tab列表', $gride->render(), true);
        }
        return $content->header('施工工序配置')->breadcrumb(
            ['text' => '施工工序列表', 'url' => url('admin/constructionPurchase/process')],
            ['text' => '施工工序配置'])
            ->row($tab->render());
    }

    private function getProcessForm($id = 0)
    {
        $info = [];
        if ($id) {
            $info = ConstructionProcess::getInfoByWhere(['id' => $id]);
        }
        $form = new Form($info);
        $form->hidden('id', 'ID');
        $form->text('name', '施工工序名称')->setWidth(4, 2)->required();
        $form->imgUpload('back_img', '背景图');
        $form->imgUpload('share_img', '分享图');
        $form->text('share_title', '分享标题')->setWidth(4, 2);
        $form->text('share_desc', '分享描述')->setWidth(4, 2);
        $form->action(url('admin/constructionPurchase/process/save'));
        return $form;
    }

    private function getProcessTabGride($processId)
    {
        $list = ConstructionProcessTab::selectListByWhere(['process_id' => $processId, 'status' => ConstructionProcessTab::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);

        $gridModel = new GridDataModel($list);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->sort();
                $grid->column('name', 'tab 名称');
            }
        );
        return $grid;
    }

    public function saveProcess(Content $content, Request $request)
    {
        $id = $request->input('id', 0);
        $name = $request->input('name', '');
        $backImg = $request->input('back_img', '');
        $shareImg = $request->input('share_img', '');
        $shareTitle = $request->input('share_title', '');
        $shareDesc = $request->input('share_desc', '');
        $data = [
            'name' => $name,
            'back_img' => $backImg,
            'share_img' => $shareImg,
            'share_title' => $shareTitle,
            'share_desc' => $shareDesc,
            'status' => ConstructionProcess::STATUS_NORMAL,
        ];
        if ($id) {
            $id = ConstructionProcess::updateData($data, ['id' => $id]);
        } else {
            $id = ConstructionProcess::addData($data);
        }
        if ($id) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/constructionPurchase/process'))->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delProcess(Content $content, Request $request, $id)
    {
        $data = [
            'status' => ConstructionProcess::STATUS_DELETE
        ];
        $rs = ConstructionProcess::updateData($data, ['id' => $id]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function editTab(Content $content, Request $request, $processId, $tabId = 0)
    {
        $processInfo = ConstructionProcess::getInfoByWhere(['id' => $processId]);
        $tab = new Tab();
        $form = $this->getTabForm($processId, $tabId);
        $tab->add($processInfo['name'] . '-Tab基础信息', $form);
        if ($tabId) {
            $tabInfo = ConstructionProcessTab::getInfoByWhere(['id' => $tabId]);
            $gride = $this->getTabModuleGride($processId, $tabId);
            $tab->add($tabInfo['name'] . '-模块列表', $gride->render(), true);
        }
        $header = $processInfo['name'] . '-Tab信息';
        return $content->header($header)->breadcrumb(
            ['text' => '施工工序列表', 'url' => url('admin/constructionPurchase/process')],
            ['text' => 'Tab信息'])
            ->row($tab->render());
    }

    private function getTabForm($processId, $tabId = 0)
    {
        $info = [];
        if ($tabId) {
            $info = ConstructionProcessTab::getInfoByWhere(['id' => $tabId]);
        } else {
            $info['process_id'] = $processId;
        }
        $form = new Form($info);
        $form->hidden('id', 'ID');
        $form->text('process_id', '工序ID')->setWidth(4, 2)->readonly();;
        $form->text('name', 'tab名称')->setWidth(4, 2)->required();
        $form->action(url('admin/constructionPurchase/process/saveTab'));
        return $form;
    }

    private function getTabModuleGride($processId, $tabId)
    {
        $list = ConstructionProcessModule::selectListByWhere(['tab_id' => $tabId, 'status[!]' => ConstructionProcessModule::STATUS_DELETE, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);

        $gridModel = new GridDataModel($list);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($processId, $tabId) {
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                //添加按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $processId, $tabId) {
                    $tool->append($this->getModuleToolbar($grid));
                    $preivewUrl = Hhzurl::H5ConstructionProcessLink($processId, $tabId);
                    $tool->append(new PreviewButton($preivewUrl));
                });
                $grid->column('id', 'ID')->sort();
                $grid->column('name', '模块名称');
                $grid->column('type', '模块类型')->display(function () {
                    return ConstructionProcessModule::MODULE_TYPE_MAP[$this->type];
                });
                $grid->column('status', '状态')->switch([
                    'on' => ['value' => ConstructionProcessModule::STATUS_NORMAL, 'text' => '展示', 'color' => 'primary'],
                    'off' => ['value' => ConstructionProcessModule::STATUS_HIDE, 'text' => '隐藏', 'color' => 'default'],
                ]);
            }
        );
        return $grid;
    }

    private function getModuleToolbar($grid)
    {
        $tools = '';
        foreach (ConstructionProcessModule::MODULE_TYPE_MAP as $type => $typeVal) {
            $href = $grid->resource() . '/addModule/' . $type;
            $tools .= "<li><a href='$href'>" . $typeVal . "</a></li>";
        }
        return <<<TOOLS
<div class="btn-group pull-right" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="添加"><i class="fa fa-plus"></i><span class="hidden-xs"> 添加</span></a>
    <button type="button" class="btn btn-sm btn-twitter dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul id="menu3" class="dropdown-menu" aria-labelledby="drop6">
      $tools
    </ul>
</div>
TOOLS;
    }


    public function saveTab(Content $content, Request $request)
    {
        $id = $request->input('id', 0);
        $name = $request->input('name', '');
        $processId = $request->input('process_id', 0);
        if ($processId) {
            $data = [
                'name' => $name,
                'process_id' => $processId,
                'status' => ConstructionProcessTab::STATUS_NORMAL,
            ];
            if ($id) {
                $id = ConstructionProcessTab::updateData($data, ['id' => $id]);
            } else {
                $id = ConstructionProcessTab::addData($data);
            }
            if ($id) {
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect(url('/admin/constructionPurchase/process/' . $processId . '/edit'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } else {
            $error = new MessageBag([
                'title' => '不存在的process_Id'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delTab(Content $content, Request $request, $processId, $tabId)
    {
        $data = [
            'status' => ConstructionProcessTab::STATUS_DELETE
        ];
        $rs = ConstructionProcessTab::updateData($data, ['id' => $tabId]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortTab(Content $content, Request $request, $processId)
    {
        $sortInfo = $request->input('sort', null);
        if ($sortInfo && is_array($sortInfo)) {
            foreach ($sortInfo as $key => $val) {
                foreach ($sortInfo as $key => $val) {
                    ConstructionProcessTab::updateData(['sort' => $val], ['id' => $key]);
                }
            }
        }
    }

    public function addModule(Content $content, $processId, $tabId, $moduleType)
    {
        $processInfo = ConstructionProcess::getInfoByWhere(['id' => $processId]);
        $tabInfo = ConstructionProcessTab::getInfoByWhere(['id' => $tabId]);
        $header = '施工工序' . '-' . $processInfo['name'] . '-' . $tabInfo['name'] . '-';
        switch ($moduleType) {
            case ConstructionProcessModule::MODULE_TYPE_CORE_KNOWLEDGE:
                $header = $header . '核心知识点模块';
                break;
            case ConstructionProcessModule::MODULE_TYPE_MUST_KNOW_TIPS:
                $header = $header . '必知Tips模块';
                break;
            case ConstructionProcessModule::MODULE_TYPE_BANNER:
                $header = $header . 'banner模块';
                break;
            case ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND:
                $header = $header . 'note推荐模块';
                break;
        }
        $form = $this->getModuleForm($processId, $tabId, [], $moduleType);
        return $content->header($header)->breadcrumb(
            ['text' => '施工工序列表', 'url' => url('admin/constructionPurchase/process')],
            ['text' => '模块列表', 'url' => url('admin/constructionPurchase/process/' . $processId . '/edit/' . $tabId . '/edit')],
            ['text' => '模块信息'])
            ->row($form->render());
    }

    public function editModule(Content $content, Request $request, $processId, $tabId, $moduleId)
    {
        $processInfo = ConstructionProcess::getInfoByWhere(['id' => $processId]);
        $tabInfo = ConstructionProcessTab::getInfoByWhere(['id' => $tabId]);
        $moduleInfo = ConstructionProcessModule::getInfoByWhere(['id' => $moduleId]);
        $tab = new Tab();
        $form = $this->getModuleForm($processId, $tabId, $moduleInfo, $moduleInfo['type']);
        $tab->add($moduleInfo['name'] . '模块-基础信息', $form);
        if ($moduleId) {
            $gride = $this->getTabModuleContentGride($moduleId, $moduleInfo);
            $tab->add($moduleInfo['name'] . '模块-内容列表', $gride->render(), true);
        }
        $header = '施工工序' . '-' . $processInfo['name'] . '-' . $tabInfo['name'] . '-' . $moduleInfo['name'] . '模块信息';
        return $content->header($header)->breadcrumb(
            ['text' => '施工工序列表', 'url' => url('admin/constructionPurchase/process')],
            ['text' => '模块列表', 'url' => url('admin/constructionPurchase/process/' . $processId . '/edit/' . $tabId . '/edit')],
            ['text' => '模块信息'])
            ->row($tab->render());
    }

    private function getModuleForm($processId, $tabId, $moduleInfo, $moduleType)
    {
        $moduleInfo['process_id'] = $processId;
        $moduleInfo['tab_id'] = $tabId;
        $moduleInfo['type'] = $moduleType;
        switch ($moduleType) {
            case ConstructionProcessModule::MODULE_TYPE_CORE_KNOWLEDGE:
                $moduleInfo['name'] = '核心知识点';
                break;
            case ConstructionProcessModule::MODULE_TYPE_MUST_KNOW_TIPS:
                $moduleInfo['name'] = '必知Tips';
                break;
            case ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND:
                $moduleInfo['name'] = '住友经验';
                break;
        }
        $form = new Form($moduleInfo);
        $form->hidden('id', 'ID');
        $form->hidden('process_id', '工序ID');
        $form->hidden('tab_id', '工序TabID');
        $form->hidden('type', '模块类型');
        $form->text('name', '模块名称')->required();
        $form->action(url('admin/constructionPurchase/process/saveModule'));
        return $form;
    }

    private function getTabModuleContentGride($moduleId, $moduleInfo)
    {
        $list = ConstructionProcessModuleContent::selectListByWhere(['module_id' => $moduleId, 'status' => ConstructionProcessModuleContent::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);

        $gridModel = new GridDataModel($list);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($moduleId, $moduleInfo) {
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->sort();
                switch ($moduleInfo['type']) {
                    case ConstructionProcessModule::MODULE_TYPE_CORE_KNOWLEDGE:
                        $grid->column('text', '正文');
                        break;
                    case ConstructionProcessModule::MODULE_TYPE_MUST_KNOW_TIPS:
                        $grid->column('title', '标题');
                        $grid->column('text', '正文');
                        $grid->column('img_url', '图片')->image();
                        break;
                    case ConstructionProcessModule::MODULE_TYPE_BANNER:
                        $grid->column('img_url', 'banner')->image();
                        $grid->column('link', '链接地址')->linkSelect(false);
                        break;
                    case ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND:
                        $grid->tools(function (Grid\Tools $tools) use ($moduleId) {
                            $url = url('/admin/constructionPurchase/process/module/content/searchkeyword?moduleId=' . $moduleId);
                            $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-success" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'500px\', \'600px\'],
                                content: \'' . $url . '\'
                            });" title="链接">搜索结果</a>
</div>');
                        });
                        $grid->column('keyword', '关键词/note ID')->display(function () {
                            if ($this->keyword) {
                                return $this->keyword;
                            } else if ($this->obj_id) {
                                return $this->obj_id;
                            }
                        })->width(1000);
                        break;
                }
            }
        );
        return $grid;
    }

    public function saveModule(Content $content, Request $request)
    {
        $id = $request->input('id', 0);
        $data = [
            'process_id' => $request->input('process_id', 0),
            'tab_id' => $request->input('tab_id', 0),
            'type' => $request->input('type', 0),
            'name' => $request->input('name', ''),
            'status' => ConstructionProcessModule::STATUS_NORMAL,
        ];
        if (empty($data['process_id']) || empty($data['tab_id'])) {
            $error = new MessageBag([
                'title' => '工序或则tab_id错误'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        if ($id) {
            $id = ConstructionProcessModule::updateData($data, ['id' => $id]);
        } else {
            $id = ConstructionProcessModule::addData($data);
        }
        if ($id) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/constructionPurchase/process/' . $data['process_id'] . '/edit/' . $data['tab_id'] . '/edit'))->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delModule(Content $content, Request $request, $processId, $tabId, $moduleId)
    {
        $data = [
            'status' => ConstructionProcessModule::STATUS_DELETE
        ];
        $rs = ConstructionProcessModule::updateData($data, ['id' => $moduleId]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortModule(Content $content, Request $request, $processId, $tabId)
    {
        $sortInfo = $request->input('sort', null);
        if ($sortInfo && is_array($sortInfo)) {
            foreach ($sortInfo as $key => $val) {
                foreach ($sortInfo as $key => $val) {
                    ConstructionProcessModule::updateData(['sort' => $val], ['id' => $key]);
                }
            }
        }
    }

    public function switchModule(Content $content, Request $request, $processId, $tabId, $moduleId)
    {
        $status = $request->input('status', null);
        if (!is_null($status) && $moduleId > 0) {
            $status = $status ? ConstructionProcessModule::STATUS_NORMAL : ConstructionProcessModule::STATUS_HIDE;
            $result = ConstructionProcessModule::updateData(['status' => $status], ['id' => $moduleId]);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "success",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "修改失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    public function editModuleContent(Content $content, Request $request, $processId, $tabId, $moduleId, $contentId = 0)
    {
        $processInfo = ConstructionProcess::getInfoByWhere(['id' => $processId]);
        $tabInfo = ConstructionProcessTab::getInfoByWhere(['id' => $tabId]);
        $moduleInfo = ConstructionProcessModule::getInfoByWhere(['id' => $moduleId]);
        $moduleContentInfo = $contentId ? ConstructionProcessModuleContent::getInfoByWhere(['id' => $contentId]) : [];
        $moduleContentInfo['process_id'] = $processId;
        $moduleContentInfo['tab_id'] = $tabId;
        $moduleContentInfo['module_id'] = $moduleId;
        $moduleContentInfo['module_type'] = $moduleInfo['type'];
        if ($moduleContentInfo['module_type'] == ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND) {
            $moduleContentInfo['recommend_type'] = 0;
            if (isset($moduleContentInfo['obj_id'])) {
                $moduleContentInfo['recommend_type'] = 1;
            }
        }
        $tab = new Tab();
        $form = new Form($moduleContentInfo);
        $form->hidden('id', 'ID');
        $form->hidden('process_id', '工序ID');
        $form->hidden('tab_id', '工序TabID');
        $form->hidden('module_id', '模块ID');
        $form->hidden('module_type', $moduleInfo['type']);
        switch ($moduleInfo['type']) {
            case ConstructionProcessModule::MODULE_TYPE_CORE_KNOWLEDGE:
                $form->text('text', '核心知识点文本')->required();
                break;
            case ConstructionProcessModule::MODULE_TYPE_MUST_KNOW_TIPS:
                $form->text('title', '必知Tips内容标题')->required();
                $form->textarea('text', '必知Tips内容正文')->required();
                $form->imgUpload('img', '必知Tips图片');
                break;
            case ConstructionProcessModule::MODULE_TYPE_BANNER:
                $form->imgUpload('img', 'banner');
                $form->linkSelect('link', '跳转链接');
                break;
            case ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND:
                $form->radio('recommend_type', '类型')->required()
                    ->options([
                        0 => '搜索关键词',
                        1 => 'note ID',
                    ])->when(0, function (Form $form) {
                        $form->text('keyword', '搜索关键词');
                    })->when(1, function (Form $form) {
                        $form->textarea('obj_id', 'note ID')->help('多个note id以英文逗号(,)隔开')->rows(10);
                    })
                    ->default(0);
                break;
        }
        $form->action(url('admin/constructionPurchase/process/saveModuleContent'));
        $header = '施工工序' . '-' . $processInfo['name'] . '-' . $tabInfo['name'] . '-' . $moduleInfo['name'] . '模块内容';;
        $tab->add($header, $form);
        return $content->header($header)->breadcrumb(
            ['text' => '施工工序列表', 'url' => url('admin/constructionPurchase/process')],
            ['text' => '模块列表', 'url' => url('admin/constructionPurchase/process/' . $processId . '/edit/' . $tabId . '/edit')],
            ['text' => '模块内容列表', 'url' => url('admin/constructionPurchase/process/' . $processId . '/edit/' . $tabId . '/edit/' . $moduleId . '/edit')],
            ['text' => '模块内容'])
            ->row($tab->render());
    }

    public function saveModuleContent(Content $content, Request $request)
    {
        $id = $request->input('id', 0);
        $moduleId = $request->input('module_id', 0);
        $moduleInfo = ConstructionProcessModule::getInfoByWhere(['id' => $moduleId]);
        $moduleType = $moduleInfo['type'];
        $tabId = $moduleInfo['tab_id'];
        $processId = $moduleInfo['process_id'];
        $content = [];
        switch ($moduleType) {
            case ConstructionProcessModule::MODULE_TYPE_CORE_KNOWLEDGE:
                $content['text'] = trim($request->input('text', ''));
                break;
            case ConstructionProcessModule::MODULE_TYPE_MUST_KNOW_TIPS:
                $content['title'] = trim($request->input('title', ''));
                $content['text'] = trim($request->input('text', ''));
                $content['img'] = $request->input('img', '');
                break;
            case ConstructionProcessModule::MODULE_TYPE_BANNER:
                $content['img'] = trim($request->input('img', ''));
                $linkType = $request->input('link_type', '');
                $linkParams = $request->input('link_params', '');
                $content['link_type'] = $linkType;
                $content['link_params'] = $linkParams;
                break;
            case ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND:
                $recommendType = $request->input('recommend_type', 0);
                if (0 == $recommendType) {
                    $keyword = trim($request->input('keyword', ''));
                    $keyword = str_replace(["\r\n", "\r", "\n", "，"], ",", $keyword);
                    $content['keyword'] = $keyword;
                } else if (1 == $recommendType) {
                    $objId = trim($request->input('obj_id', ''));
                    $objId = str_replace(["\r\n", "\r", "\n", "，"], ",", str_replace(" ", "", $objId));
                    $content['obj_id'] = $objId;
                }
                break;
        }
        $data = [
            'process_id' => $processId,
            'module_id' => $moduleId,
            'module_type' => $moduleType,
            'content' => $content ? json_encode($content, JSON_UNESCAPED_UNICODE) : '',
            'status' => ConstructionProcessModuleContent::STATUS_NORMAL,
        ];
        if (empty($data['process_id']) || empty($data['module_id'])) {
            $error = new MessageBag([
                'title' => '工序或则模块id错误'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        if ($id) {
            $id = ConstructionProcessModuleContent::updateData($data, ['id' => $id]);
        } else {
            $id = ConstructionProcessModuleContent::addData($data);
        }
        if ($id) {
            if ($moduleType == ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND) {
                Construction::getProcessModuleRecommendNote($moduleId, true);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/constructionPurchase/process/' . $processId . '/edit/' . $tabId . '/edit/' . $moduleId . '/edit'))->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delModuleContent(Content $content, Request $request, $processId, $tabId, $moduleId, $contentId)
    {
        $contentInfo = ConstructionProcessModuleContent::getInfoByWhere(['id' => $contentId]);
        $data = [
            'status' => ConstructionProcessModuleContent::STATUS_DELETE
        ];
        $rs = ConstructionProcessModuleContent::updateData($data, ['id' => $contentId]);
        if ($contentInfo['module_type'] == ConstructionProcessModule::MODULE_TYPE_NOTE_RECOMMEND) {
            Construction::getProcessModuleRecommendNote($moduleId, true);
        }
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortModuleContent(Content $content, Request $request, $processId, $tabId, $moduleId)
    {
        $sortInfo = $request->input('sort', null);
        if ($sortInfo && is_array($sortInfo)) {
            foreach ($sortInfo as $key => $val) {
                foreach ($sortInfo as $key => $val) {
                    ConstructionProcessModuleContent::updateData(['sort' => $val], ['id' => $key]);
                }
            }
        }
    }

    public function previewSearchKeyword(Content $content, Request $request)
    {
        $moduleId = $request->input('moduleId', 0);
        if ($moduleId) {
            $list = ConstructionProcessModuleContent::selectListByWhere(['module_id' => $moduleId, 'status' => ConstructionProcessModuleContent::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);
            $keywords = [];
            foreach ($list as $row) {
                $keywords[] = $row['keyword'];
            }
            $result = Construction::searchNoteIdsByKeywords($keywords);
            $form = new Form(['keyword' => $result]);
        }
        $form->textarea('keyword', '「' . implode(',', $keywords) . '」搜索结果')->rows(20);
        $form->disableReset();
        $form->disableSubmit();
        return $content
            ->header('搜索词「' . implode(',', $keywords) . '」结果预览')
            ->row($form);
    }

}